package unv.esiag.uchiha;

import java.awt.BorderLayout;

import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;

import unv.esiag.uchiha.core.Agent;
import unv.esiag.uchiha.topics.STopic;
import unv.esiag.uchiha.topics.Topic;
import unv.esiag.uchiha.topics.TopicListener;

public class TreePanel extends JPanel implements TopicListener, TreeSelectionListener{
	private static final long serialVersionUID = 1L;
	
	private JTree tree;
	private STopic selectedTopic;
	public TreePanel() {
		tree = new JTree();
		setLayout(new BorderLayout());
		tree.addTreeSelectionListener(this);
		add(tree);
		topicModified(Agent.getInstance().getRoot());
	}
	private void createNode(DefaultMutableTreeNode node, STopic stopic){
		node.setUserObject(stopic);
		for(int i = 0;i<stopic.size();i++){
			DefaultMutableTreeNode node1 = new DefaultMutableTreeNode();
			createNode(node1, stopic.get(i));
			node.add(node1);
		}
	}
	public void cacheModified(Topic topic) {
		STopic stopic = topic.createSTopic();//Agent.getInstance().getRoot().createSTopic();
		DefaultMutableTreeNode node = new DefaultMutableTreeNode();
		createNode(node, stopic);
		tree = new JTree(node);
		tree.addTreeSelectionListener(this);
		remove(0);
		add(tree);
		this.validate();
		//this.validateTree();
		this.invalidate();
	}
	public void topicModified(Topic topic) {
		STopic stopic = topic.createSTopic();//Agent.getInstance().getRoot().createSTopic();
		DefaultMutableTreeNode node = new DefaultMutableTreeNode();
		createNode(node, stopic);
		tree = new JTree(node);
		tree.addTreeSelectionListener(this);
		remove(0);
		add(tree);
		this.validate();
		//this.validateTree();
		this.invalidate();
	}
	public void valueChanged(TreeSelectionEvent e) {
		DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
		if(node != null){
			selectedTopic = (STopic)node.getUserObject();
		}
	}
	public STopic getSelectedTopic(){
		return selectedTopic;
	}
}
